package com.mpgame.common.network;

import com.mpgame.common.utils.Log;
import com.mpgame.common.constants.Constants.CGrpc;

import io.grpc.Channel;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.concurrent.TimeUnit;

public class GrpcClient {
    private final ManagedChannel channel;
    private final String target;

    public GrpcClient(String target){
        this.target = target;
        this.channel = createManagedChannel();
    }
    private ManagedChannel createManagedChannel(){
        return ManagedChannelBuilder.forTarget(target)
                .usePlaintext()
                // 心跳检测配置
                .keepAliveTime(CGrpc.KEEP_ALIVE_TIME_SEC, CGrpc.TIME_UNIT)
                .keepAliveTimeout(CGrpc.KEEP_ALIVE_TIMEOUT_SEC, CGrpc.TIME_UNIT)
                .keepAliveWithoutCalls(CGrpc.KEEP_ALIVE_WITHOUT_CALLS)
                // 消息大小限制
                .maxInboundMessageSize(CGrpc.MAX_INBOUND_MSG_BYTES)
                .maxInboundMetadataSize(CGrpc.MAX_INBOUND_METADATA_BYTES)
                // 重试配置
                .enableRetry()
                .maxRetryAttempts(CGrpc.MAX_RETRY_ATTEMPTS)
                .retryBufferSize(1 << 16)
                .perRpcBufferLimit(1 << 20)
                .build();
    }
    public Channel getChannel(){
        return channel;
    }
    public boolean isHealthy(){
        try{
            return channel != null && 
                !channel.isShutdown() &&
                !channel.isTerminated();
        }
        catch(Exception e){
            Log.debug("GrpcClient::连接健康检查失败：" + e.getMessage());
            return false;
        }
    }

    public void shutdown(){
        try{
            channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
            Log.info("gRPC客户端已关闭：" + target);
        }
        catch(InterruptedException e){
            Log.err("gRPC客户端关闭失败：" + e.getMessage());
        }
    }
}
